package com.aracky.system.service.impl;

import com.aracky.common.util.ConvertUtil;
import com.aracky.system.mapper.SysTableLineMapper;
import com.aracky.system.model.entity.SysTableLine;
import com.aracky.system.model.form.SysTableLineForm;
import com.aracky.system.service.SysTableLineService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 表头行信息表 服务实现类
 * </p>
 *
 * @author zengzhiping
 * @since 2022-07-18 10:05:44
 */
@Service
public class SysTableLineServiceImpl extends ServiceImpl<SysTableLineMapper, SysTableLine> implements SysTableLineService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateTableLine(Long headId, List<SysTableLineForm> sysTableLineList) {

        if (sysTableLineList == null || sysTableLineList.isEmpty()) {
            return;
        }

        List<SysTableLine> sysTableLines = ConvertUtil.sourceToTargets(sysTableLineList, SysTableLine.class);
        sysTableLines.forEach(e -> e.setHeadId(headId));


        //去掉不存在的数据
        LambdaQueryWrapper<SysTableLine> lineLambdaQueryWrapper =
                Wrappers.<SysTableLine>lambdaQuery().select(SysTableLine::getLineId)
                        .eq(SysTableLine::getHeadId, headId);
        List<SysTableLine> list = this.list(lineLambdaQueryWrapper);

        List<Long> exisIdList = sysTableLines.stream().map(SysTableLine::getLineId).collect(Collectors.toList());

        List<Long> noExistsId = list.stream()
                .filter(item -> !exisIdList.contains(item.getLineId()))
                .map(SysTableLine::getLineId)
                .collect(Collectors.toList());

        //删除数据
        if (noExistsId != null && !noExistsId.isEmpty()) {
            this.removeBatchByIds(noExistsId);
        }

        this.saveOrUpdateBatch(sysTableLines);
    }
}
